package com.micro.train.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 座位库存状态实体类（7天滚动窗口）
 */
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("座位库存状态")
public class SeatInventory {
    
    @TableId(value = "库存ID", type = IdType.AUTO)
    private Long inventoryId;
    
    @TableField("座位ID")
    private Long seatId;
    
    @TableField("列车ID")
    private Long trainId;
    
    @TableField("7天状态串")
    private String sevenDayStatus; // 7位字符串，1=可用，0=已售
    
    @TableField("基准日期")
    private LocalDate baseDate; // 7天窗口的起始日期
    
    @TableField(value = "创建时间", fill = FieldFill.INSERT)
    private LocalDateTime createTime;
    
    @TableField(value = "更新时间", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;
    
    @TableLogic
    @TableField("deleted")
    private Integer deleted;
    
    /**
     * 检查指定日期是否可用
     * @param targetDate 目标日期
     * @return true=可用，false=已售
     */
    public boolean isAvailable(LocalDate targetDate) {
        int dayOffset = calculateDayOffset(targetDate);
        if (dayOffset >= 0 && dayOffset < 7) {
            char status = sevenDayStatus.charAt(dayOffset);
            // 添加调试信息
            System.out.println("DEBUG - 座位ID: " + seatId + 
                             ", 基准日期: " + baseDate + 
                             ", 目标日期: " + targetDate + 
                             ", 偏移量: " + dayOffset + 
                             ", 状态串: " + sevenDayStatus + 
                             ", 位置" + dayOffset + "的状态: " + status + 
                             ", 是否可用: " + (status == '1'));
            return status == '1';
        }
        System.out.println("DEBUG - 座位ID: " + seatId + 
                         ", 基准日期: " + baseDate + 
                         ", 目标日期: " + targetDate + 
                         ", 偏移量: " + dayOffset + 
                         ", 超出范围，返回false");
        return false;
    }
    
    /**
     * 标记指定日期为已售
     * @param targetDate 目标日期
     * @return true=成功，false=失败
     */
    public boolean markAsSold(LocalDate targetDate) {
        int dayOffset = calculateDayOffset(targetDate);
        if (dayOffset >= 0 && dayOffset < 7 && sevenDayStatus.charAt(dayOffset) == '1') {
            char[] statusArray = sevenDayStatus.toCharArray();
            statusArray[dayOffset] = '0';
            sevenDayStatus = new String(statusArray);
            return true;
        }
        return false;
    }
    
    /**
     * 标记指定日期为可用
     * @param targetDate 目标日期
     * @return true=成功，false=失败
     */
    public boolean markAsAvailable(LocalDate targetDate) {
        int dayOffset = calculateDayOffset(targetDate);
        if (dayOffset >= 0 && dayOffset < 7) {
            char[] statusArray = sevenDayStatus.toCharArray();
            statusArray[dayOffset] = '1';
            sevenDayStatus = new String(statusArray);
            return true;
        }
        return false;
    }
    
    /**
     * 计算目标日期在7天窗口中的偏移量
     * @param targetDate 目标日期
     * @return 偏移量（0-6），-1表示超出范围
     */
    public int calculateDayOffset(LocalDate targetDate) {
        if (baseDate == null || targetDate == null) {
            return -1;
        }
        
        long daysDiff = java.time.temporal.ChronoUnit.DAYS.between(baseDate, targetDate);
        if (daysDiff >= 0 && daysDiff < 7) {
            return (int) daysDiff;
        }
        return -1;
    }
    
    /**
     * 获取指定日期的状态
     * @param targetDate 目标日期
     * @return '1'=可用，'0'=已售，null=超出范围
     */
    public Character getStatusForDate(LocalDate targetDate) {
        int dayOffset = calculateDayOffset(targetDate);
        if (dayOffset >= 0 && dayOffset < 7) {
            return sevenDayStatus.charAt(dayOffset);
        }
        return null;
    }
    
    /**
     * 获取可用座位数量
     * @return 7天中可用的天数
     */
    public int getAvailableDays() {
        return (int) sevenDayStatus.chars()
                .mapToObj(ch -> (char) ch)
                .filter(ch -> ch == '1')
                .count();
    }
    
    /**
     * 获取已售座位数量
     * @return 7天中已售的天数
     */
    public int getSoldDays() {
        return (int) sevenDayStatus.chars()
                .mapToObj(ch -> (char) ch)
                .filter(ch -> ch == '0')
                .count();
    }
    
    /**
     * 检查是否全部售罄
     * @return true=全部售罄，false=还有可用
     */
    public boolean isSoldOut() {
        return sevenDayStatus.equals("0000000");
    }
    
    /**
     * 获取状态字符串的详细描述
     * @return 状态描述
     */
    public String getStatusDescription() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 7; i++) {
            LocalDate date = baseDate.plusDays(i);
            char status = sevenDayStatus.charAt(i);
            sb.append(String.format("第%d天(%s): %s, ", i + 1, date, status == '1' ? "可用" : "已售"));
        }
        return sb.toString().replaceAll(", $", "");
    }
}
